#![cfg_attr(
  all(not(debug_assertions), target_os = "windows"),
  windows_subsystem = "windows"
)]

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
  format!("Hello, {}! You've been greeted from Rust!", name)
}

use tauri::{CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu};

fn main() {
  let quit = CustomMenuItem::new("quit".to_string(), "退出");
  let show = CustomMenuItem::new("show".to_string(), "显示/最小化");

  let tray_menu = SystemTrayMenu::new().add_item(show).add_item(quit);

  let tray = SystemTray::new().with_menu(tray_menu);
  tauri::Builder::default()
  .system_tray(tray)
      .on_system_tray_event(|_app, event| match event {
          // 双击托盘
          SystemTrayEvent::DoubleClick {
            position: _,
            size: _,
            ..
          } => {
            let window = _app.get_window("main").unwrap();
            if window.is_visible().unwrap() {
              window.hide().unwrap();
            } else {
              window.show().unwrap();
            }
          }
          // 点击托盘菜单
          SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
              "quit" => {
                  std::process::exit(0);
              }
              "show" => {
                let window = _app.get_window("main").unwrap();
                if window.is_visible().unwrap() {
                  window.hide().unwrap();
                } else {
                  window.show().unwrap();
                }
              }
              _ => {}

          }
          _ => {}
      })
      .invoke_handler(tauri::generate_handler![greet])
      .run(tauri::generate_context!())
      .expect("error while running tauri application");
}